package app.itgungnir.compose.wan.business.settings

import androidx.compose.runtime.Composable
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Modifier
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.navigation.compose.rememberNavController
import app.itgungnir.compose.wan.widgets.WanAlertDialog
import app.itgungnir.compose.wan.widgets.WanScaffold
import com.google.accompanist.insets.navigationBarsPadding

@Composable
fun SettingsScreen(navController: NavController = rememberNavController()) {
    val viewModel = viewModel<SettingsViewModel>()
    val clearCacheDialogState = remember { mutableStateOf(false) }
    // UI
    WanScaffold(
        modifier = Modifier.navigationBarsPadding(),
        title = "系统设置",
        navController = navController
    ) {
        SettingsUI(
            showHotArticlesState = viewModel.showHotArticlesState.collectAsState(initial = true),
            onShowHotArticlesToggled = { viewModel.toggleShowHotArticles(it) },
            nonPictureModeState = viewModel.nonPictureModeState.collectAsState(initial = false),
            onNonPictureModeToggled = { viewModel.toggleNonPictureMode(it) },
            cacheSizeState = viewModel.cacheSizeState.collectAsState(),
            onClearCacheSize = {
                viewModel.dismissDialogState.value = false
                clearCacheDialogState.value = true
            },
            darkModeExtendSystemState = viewModel.darkModeExtendSystemState.collectAsState(initial = true),
            onDarkModeExtendSystemToggled = { viewModel.toggleDarkModeExtendSystem(it) },
            darkModeEnabledState = viewModel.darkModeEnabledState.collectAsState(initial = false),
            onDarkModeEnabledToggled = { viewModel.toggleDarkModeEnabled(it) },
            colorPaletteIndexState = viewModel.colorPaletteIndexState.collectAsState(initial = 0),
            onColorPaletteIndexChanged = { viewModel.toggleColorPaletteIndex(it) },
            fontSizeIndexState = viewModel.fontSizeIndexState.collectAsState(initial = 0),
            onFontSizeIndexChanged = { viewModel.toggleFontSizeIndex(it) }
        )
    }
    WanAlertDialog(
        state = clearCacheDialogState,
        title = "清除缓存确认",
        message = "清除缓存将清除数据库等所有本地持久化数据，是否确定清除应用内所有缓存？",
        loadingState = viewModel.loadingState.collectAsState(),
        loadingJob = viewModel.loadingJob,
        dismissState = viewModel.dismissDialogState.collectAsState(),
        errorState = viewModel.errorState.collectAsState(initial = null),
        negativeText = "再想想",
        negativeCallback = { clearCacheDialogState.value = false },
        positiveText = "确定",
        positiveCallback = { viewModel.clearCache() })
}
